package website

import (
	"context"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
)

type SetRequest struct {
	Hostname string `json:"hostname" validate:"required" binding:"required,hostname"` // 域名
	Tls      struct {
		Enable   bool   `json:"enable" validate:"required"`                                      // 是否启用TLS
		Custom   bool   `json:"custom" validate:"required"`                                      // 自定义TLS证书
		CertPath string `json:"cert_path" validate:"required" binding:"required_if=Custom true"` // 证书路径
		KeyPath  string `json:"key_path" validate:"required" binding:"required_if=Custom true"`  // 私钥路径
	} `json:"tls" validate:"required"` // TLS配置
	Reverses []SetReverse `json:"reverses" validate:"required" binding:"required,min=1,dive"` // 反向代理配置
}

type SetReverse struct {
	Path   string `json:"path" validate:"required" binding:"required"`   // 匹配路径
	Target string `json:"target" validate:"required" binding:"required"` // 目标地址
}

func (cls *Website) Set(c *gin.Context) (int, any, error) {
	var body = SetRequest{}
	if err := c.ShouldBindJSON(&body); nil != err {
		return response.InvalidRequest, nil, err
	}

	var ctx = context.Background()
	var tls = new(application.CaddyWebsiteTls)
	tls.Enable = body.Tls.Enable
	tls.Custom = body.Tls.Custom
	tls.CertPath = body.Tls.CertPath
	tls.KeyPath = body.Tls.KeyPath

	var reverses = make([]*application.CaddyWebsiteReverse, 0)
	for _, reverse := range body.Reverses {
		reverses = append(reverses, &application.CaddyWebsiteReverse{Path: reverse.Path, Target: reverse.Target})
	}

	if err := cls.caddy.SetWebsite(ctx, body.Hostname, reverses, tls); nil != err {
		return response.Unknown, nil, err
	}

	// 应用配置
	if err := cls.caddy.ApplyConfig(ctx); nil != err {
		return response.Unknown, nil, err
	}

	// 重载服务
	if err := cls.caddy.Reload(ctx); nil != err {
		return response.Unknown, nil, err
	}

	return response.Ok, nil, nil
}
